/**
 * 工作项多维表格组件
 */

'use client';

import React, { useState, useMemo } from 'react';
import {
  Table,
  Tag,
  Avatar,
  Space,
  Button,
  Tooltip,
  Progress,
  Typography,
  Dropdown,
  Modal,
  message,
} from 'antd';
import {
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
  ExportOutlined,
  UserOutlined,
} from '@ant-design/icons';
import type { ColumnsType, TableProps } from 'antd/es/table';
import dayjs from 'dayjs';
import type { WorkItem } from '../types/workItem';
import { useProjects, useWorkItemMeta } from '../hooks/useWorkItems';

const { Text, Link } = Typography;

interface WorkItemTableProps extends Omit<TableProps<WorkItem>, 'columns' | 'dataSource'> {
  workItems: WorkItem[];
  allWorkItems?: WorkItem[]; // 添加所有工作项数据
  loading?: boolean;
  total?: number;
  currentPage?: number;
  pageSize?: number;
  onView?: (workItem: WorkItem) => void;
  onEdit?: (workItem: WorkItem) => void;
  onDelete?: (workItem: WorkItem) => void;
  onExport?: (workItems: WorkItem[]) => void;
  onPageChange?: (page: number, pageSize: number) => void;
  projectId?: string;
}

export default function WorkItemTable({
  workItems,
  allWorkItems, // 添加所有工作项数据
  loading = false,
  total,
  currentPage = 1,
  pageSize = 100,
  onView,
  onEdit,
  onDelete,
  onExport,
  onPageChange,
  projectId,
  ...tableProps
}: WorkItemTableProps) {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const { projects } = useProjects();
  const { users } = useWorkItemMeta(projectId);

  // 生成负责人筛选选项 - 从所有查询结果中提取
  const getAssigneeFilters = useMemo(() => {
    // 如果提供了所有工作项数据，则从所有数据中提取唯一的负责人
    const itemsToProcess = allWorkItems && allWorkItems.length > 0 ? allWorkItems : workItems;
    
    const assigneeMap = new Map<string, { id: string; display_name: string }>();
    
    itemsToProcess.forEach(item => {
      if (item.assignee) {
        assigneeMap.set(item.assignee.id, {
          id: item.assignee.id,
          display_name: item.assignee.display_name
        });
      }
    });

    return Array.from(assigneeMap.values()).map(assignee => ({
      text: assignee.display_name,
      value: assignee.id
    }));
  }, [workItems, allWorkItems]);

  // 生成项目筛选选项 - 从所有查询结果中提取
  const getProjectFilters = useMemo(() => {
    // 如果提供了所有工作项数据，则从所有数据中提取唯一的项目
    const itemsToProcess = allWorkItems && allWorkItems.length > 0 ? allWorkItems : workItems;
    
    const projectMap = new Map<string, { id: string; name: string }>();
    
    itemsToProcess.forEach(item => {
      if (item.project) {
        projectMap.set(item.project.id, {
          id: item.project.id,
          name: item.project.name
        });
      }
    });

    return Array.from(projectMap.values()).map(project => ({
      text: project.name,
      value: project.id
    }));
  }, [workItems, allWorkItems]);

  const getTypeTag = (type: string) => {
    const typeMap: Record<string, { color: string; text: string }> = {
      epic: { color: 'purple', text: '史诗' },
      feature: { color: 'blue', text: '特性' },
      story: { color: 'green', text: '用户故事' },
      task: { color: 'orange', text: '任务' },
      bug: { color: 'red', text: '缺陷' },
      issue: { color: 'gray', text: '事务' },
    };
    const config = typeMap[type] || { color: 'default', text: type };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const getPriorityColor = (priority?: string) => {
    const priorityMap: Record<string, string> = {
      highest: '#ff4d4f',
      high: '#ff7a45',
      medium: '#fadb14',
      low: '#52c41a',
      lowest: '#1890ff',
    };
    return priorityMap[priority || ''] || '#d9d9d9';
  };

  const handleDelete = (workItem: WorkItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除工作项 "${workItem.title}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: () => {
        onDelete?.(workItem);
      },
    });
  };

  const getActionMenu = (workItem: WorkItem) => ({
    items: [
      {
        key: 'view',
        label: '查看详情',
        icon: <EyeOutlined />,
        onClick: () => onView?.(workItem),
      },
      {
        key: 'edit',
        label: '编辑',
        icon: <EditOutlined />,
        onClick: () => onEdit?.(workItem),
      },
      {
        type: 'divider' as const,
      },
      {
        key: 'delete',
        label: '删除',
        icon: <DeleteOutlined />,
        danger: true,
        onClick: () => handleDelete(workItem),
      },
    ],
  });

  const columns: ColumnsType<WorkItem> = [
    {
      title: '编号',
      dataIndex: 'identifier',
      key: 'identifier',
      width: 120,
      fixed: 'left',
      sorter: (a, b) => a.identifier.localeCompare(b.identifier),
      render: (identifier: string, record) => (
        <Link onClick={() => onView?.(record)}>
          <Tag color="blue">{identifier}</Tag>
        </Link>
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 250,
      ellipsis: {
        showTitle: false,
      },
      render: (title: string, record) => (
        <Tooltip title={title}>
          <Link onClick={() => onView?.(record)} style={{ color: 'inherit' }}>
            {title}
          </Link>
        </Tooltip>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      filters: [
        { text: '史诗', value: 'epic' },
        { text: '特性', value: 'feature' },
        { text: '用户故事', value: 'story' },
        { text: '任务', value: 'task' },
        { text: '缺陷', value: 'bug' },
        { text: '事务', value: 'issue' },
      ],
      onFilter: (value, record) => record.type === value,
      render: (type: string) => getTypeTag(type),
    },
    {
      title: '状态',
      dataIndex: ['state', 'name'],
      key: 'state',
      width: 100,
      render: (_: any, record: WorkItem) => (
        <Tag color={record.state.color}>{record.state.name}</Tag>
      ),
    },
    {
      title: '优先级',
      dataIndex: ['priority', 'name'],
      key: 'priority',
      width: 100,
      sorter: (a, b) => {
        const priorityOrder = { highest: 5, high: 4, medium: 3, low: 2, lowest: 1 };
        const aOrder = priorityOrder[a.priority?.id as keyof typeof priorityOrder] || 0;
        const bOrder = priorityOrder[b.priority?.id as keyof typeof priorityOrder] || 0;
        return bOrder - aOrder;
      },
      render: (priority: string, record) => {
        if (!priority) return <Text type="secondary">-</Text>;
        return (
          <Tag color={getPriorityColor(record.priority?.id)}>
            {priority}
          </Tag>
        );
      },
    },
    {
      title: '负责人',
      dataIndex: 'assignee',
      key: 'assignee',
      width: 120,
      filters: getAssigneeFilters,
      onFilter: (value, record) => record.assignee?.id === value,
      render: (assignee: WorkItem['assignee']) => (
        assignee ? (
          <Space size="small">
            <Avatar
              size="small"
              src={assignee.avatar}
              icon={!assignee.avatar ? <UserOutlined /> : undefined}
            >
              {!assignee.avatar ? assignee.display_name?.[0] : undefined}
            </Avatar>
            <Text>{assignee.display_name}</Text>
          </Space>
        ) : (
          <Text type="secondary">未指派</Text>
        )
      ),
    },
    {
      title: '项目',
      dataIndex: ['project', 'name'],
      key: 'project',
      width: 150,
      filters: getProjectFilters,
      onFilter: (value, record) => record.project?.id === value,
      render: (projectName: string, record) => (
        <Space direction="vertical" size={0}>
          <Text strong>{projectName}</Text>
          <Text type="secondary" style={{ fontSize: 12 }}>
            {record.project.identifier}
          </Text>
        </Space>
      ),
    },
    {
      title: '故事点',
      dataIndex: 'story_points',
      key: 'story_points',
      width: 80,
      align: 'center',
      sorter: (a, b) => (a.story_points || 0) - (b.story_points || 0),
      render: (points: number) => points || <Text type="secondary">-</Text>,
    },
    {
      title: '工时',
      key: 'workload',
      width: 120,
      render: (_, record) => {
        const estimated = record.estimated_workload || 0;
        const remaining = record.remaining_workload || 0;
        const completed = Math.max(0, estimated - remaining);
        const percent = estimated > 0 ? Math.round((completed / estimated) * 100) : 0;

        return (
          <Space direction="vertical" size={0}>
            <Progress
              percent={percent}
              size="small"
              showInfo={false}
              strokeColor={percent >= 100 ? '#52c41a' : undefined}
            />
            <Text style={{ fontSize: 12 }}>
              {completed}/{estimated}h
            </Text>
          </Space>
        );
      },
    },
    {
      title: '开始时间',
      dataIndex: 'start_at',
      key: 'start_at',
      width: 120,
      sorter: (a, b) => (a.start_at || 0) - (b.start_at || 0),
      render: (timestamp: number) =>
        timestamp ? dayjs.unix(timestamp).format('YYYY-MM-DD') : <Text type="secondary">-</Text>,
    },
    {
      title: '结束时间',
      dataIndex: 'end_at',
      key: 'end_at',
      width: 120,
      sorter: (a, b) => (a.end_at || 0) - (b.end_at || 0),
      render: (timestamp: number) =>
        timestamp ? dayjs.unix(timestamp).format('YYYY-MM-DD') : <Text type="secondary">-</Text>,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 140,
      sorter: (a, b) => a.created_at - b.created_at,
      render: (timestamp: number) => (
        <Tooltip title={dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm:ss')}>
          {dayjs.unix(timestamp).format('YYYY-MM-DD')}
        </Tooltip>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      key: 'updated_at',
      width: 140,
      sorter: (a, b) => a.updated_at - b.updated_at,
      render: (timestamp: number) => (
        <Tooltip title={dayjs.unix(timestamp).format('YYYY-MM-DD HH:mm:ss')}>
          {dayjs.unix(timestamp).format('YYYY-MM-DD')}
        </Tooltip>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => onView?.(record)}
          />
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => onEdit?.(record)}
          />
          <Dropdown menu={getActionMenu(record)} trigger={['click']}>
            <Button
              type="link"
              size="small"
              icon={<MoreOutlined />}
            />
          </Dropdown>
        </Space>
      ),
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    onSelect: (record: WorkItem, selected: boolean, selectedRows: WorkItem[]) => {
      console.log('选择变更:', record, selected, selectedRows);
    },
    onSelectAll: (selected: boolean, selectedRows: WorkItem[], changeRows: WorkItem[]) => {
      console.log('全选变更:', selected, selectedRows, changeRows);
    },
  };

  const handleExport = () => {
    const selectedItems = workItems.filter(item => selectedRowKeys.includes(item.id));
    const itemsToExport = selectedItems.length > 0 ? selectedItems : workItems;

    if (itemsToExport.length === 0) {
      message.warning('没有可导出的数据');
      return;
    }

    onExport?.(itemsToExport);
  };

  const tableTitle = () => (
    <div className="flex justify-between items-center">
      <Space>
        <Text strong>工作项列表</Text>
        <Text type="secondary">
          共 {workItems.length} 项
          {selectedRowKeys.length > 0 && ` (已选择 ${selectedRowKeys.length} 项)`}
        </Text>
      </Space>
      <Space>
        <Button
          icon={<ExportOutlined />}
          onClick={handleExport}
          disabled={workItems.length === 0}
        >
          导出
        </Button>
      </Space>
    </div>
  );

  return (
    <Table
      {...tableProps}
      columns={columns}
      dataSource={workItems}
      rowKey="id"
      loading={loading}
      rowSelection={rowSelection}
      title={tableTitle}
      scroll={{ x: 1800, y: 600 }}
      pagination={{
        total: total || workItems.length,
        pageSize: pageSize,
        current: currentPage,
        pageSizeOptions: ['20', '50', '100', '200', '500', '1000'],
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: (total, range) => {
          // 修复当没有数据时的显示问题
          if (total === 0) {
            return '共 0 条';
          }
          return `第 ${range[0]}-${range[1]} 条，共 ${total} 条`;
        },
        onChange: onPageChange,
        onShowSizeChange: onPageChange,
        // 当每页显示数量大于总数时，不隐藏分页器，确保用户能看到分页信息
        hideOnSinglePage: false,
        // 确保分页逻辑正确
        showLessItems: true,
      }}
      size="small"
      locale={{
        emptyText: workItems.length === 0 && !loading ?
          (
            <div className="py-8 text-center">
              <div className="text-gray-400 mb-2">
                暂无工作项数据
              </div>
              <div className="text-sm text-gray-500">
                请在上方查询表单中选择项目或调整筛选条件
              </div>
            </div>
          ) : undefined
      }}
    />
  );
}